import React, { useEffect, useState } from 'react';
import {
  View,
  Text,
  Image,
  getBoundingClientRect,
  getElementById,
  usePageEvent,
} from '@ray-js/ray';
import styles from './index.module.less';

interface ActionButton {
  icon: string; // 图标路径
  text: string; // 按钮文字
  onPress: () => void; // 点击回调
}

interface BlurPressWrapperProps {
  children: React.ReactElement;
  onLongPress?: () => void;
  onPressOut?: () => void;
  actionButtons?: ActionButton[]; // 操作按钮
  onlyId?: string;
  verticalOffset: number;
}

export const BlurPressWrapper: React.FC<BlurPressWrapperProps> = ({
  children,
  onLongPress,
  onPressOut,
  actionButtons = [],
  onlyId,
  verticalOffset,
}) => {
  const [isLongPressed, setIsLongPressed] = useState(false);
  const [rect, setPositon] = useState({});

  const [timer, setTimer] = useState<NodeJS.Timeout | null>(null);

  const childref = React.useRef<HTMLDivElement>(null);

  const handlePressIn = () => {
    setIsLongPressed(true);
  };

  const handleAction = (callback: () => void) => {
    callback();
    setIsLongPressed(false);
  };

  const getSize = async () => {
    try {
      const element = await getElementById(onlyId);

      if (element) {
        const rect = await getBoundingClientRect(element);
        console.log('Rect:', rect);

        setPositon(rect);
      }
    } catch (error) {
      console.error('Error getting size:', error);
    }
  };
  //   return <> {children}</>;
  useEffect(() => {
  console.log("🐫 ~ file: index.tsx:69 ~ verticalOffset:", verticalOffset)

    getSize();
  }, [verticalOffset]);

  return (
    <>
      {isLongPressed && (
        <View className={styles.blurBackground} onClick={() => setIsLongPressed(false)}>
          <View className={styles.actionButtons}>
            {actionButtons.map((button, index) => (
              <View
                key={index}
                className={styles.actionButton}
                onClick={e => {
                  //   e.stopPropagation(); // 阻止事件冒泡
                  handleAction(button.onPress);
                }}
              >
                <Image src={button.icon} className={styles.actionIcon} />
                <Text className={styles.actionText}>{button.text}</Text>
              </View>
            ))}
          </View>

          <View
            ref={childref}
            id={onlyId}
            onLongPress={handlePressIn}
            style={{
              position: 'absolute',
              top: `${rect.top}px`,
              left: `${rect.left}px`,
            }}
          >
            {children}
          </View>
        </View>
      )}
      <View ref={childref} id={onlyId} onLongPress={handlePressIn}>
        {children}
      </View>
    </>
  );
};
